package com.giggle.common.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

/**
 * @author guozichen
 * @ClassName:
 * @Description: (这里用一句话描述累的作用)
 * @date 2020/8/26 17:28
 */
public class SpringBeanHelper implements ApplicationContextAware {
    private static final Logger logger = LoggerFactory.getLogger(SpringBeanHelper.class);
    private static ApplicationContext applicationContext = null;

    public SpringBeanHelper() {
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        logger.info("注入ApplicationContext到SpringBeanHelper:{}", applicationContext);
        if (SpringBeanHelper.applicationContext != null) {
            logger.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:{}", SpringBeanHelper.applicationContext);
        }

        SpringBeanHelper.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        assertContextInjected();
        return applicationContext;
    }

    public static <T> T getBean(String name) {
        assertContextInjected();
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        assertContextInjected();
        Map<String, ?> beans = applicationContext.getBeansOfType(clazz);
        T bean = null;
        if (beans != null) {
            bean = (T) beans.get(beans.keySet().iterator().next());
        }

        return bean;
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        assertContextInjected();
        return applicationContext.getBean(name, clazz);
    }

    public static Map<String, ?> getBeansOfType(Class<?> clazz) {
        assertContextInjected();
        Map<String, ?> beans = applicationContext.getBeansOfType(clazz);
        return beans;
    }

    public void destroy() {
        clear();
    }

    public static void clear() {
        logger.debug("清除SpringBeanHelper中的ApplicationContext:{}", applicationContext);
        applicationContext = null;
    }

    private static void assertContextInjected() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext未注入,请在spring.xml或注解中定义SpringBeanHelper");
        }
    }
}

